// @flow
import React from 'react'
import { DatePicker, Form, Input, Select, Button, message, Upload, Icon } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './Home.css'
import moment from 'moment'
const Dragger = Upload.Dragger
import { connect } from 'react-redux'
type Props = {
  userId: string,
  form: Object,
  history: Object
}

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type States = {
  data: Array<any>,
  loading: boolean,
  customers: Array<Object>,
  owner: Array<Object>,
  fileList: Array<Object>,
  customerId: string,
  userId: string
}
class ReportAdd extends React.Component {
  props: Props
  state: States
  goBack: Function
  checkNum: Function
  beforeUpload: Function
  changeFile1: Function
  changeCustomer: Function
  changeUser: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      data: [],
      loading: false,
      customers: [],
      owner: [],
      fileList: [],
      customerId: '',
      userId: ''
    }

    this.goBack = this.goBack.bind(this)
    this.checkNum = this.checkNum.bind(this)
    this.changeFile1 = this.changeFile1.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.changeCustomer = this.changeCustomer.bind(this)
    this.changeUser = this.changeUser.bind(this)
  }

  componentDidMount () {
    this.getCustomers()
    this.getUsers()
  }

  changeCustomer (value) {
    this.setState({
      customerId: value
    })
  }
  changeUser (value) {
    this.setState({
      userId: value
    })
  }

  checkNum (rule, value, callback) {
    const checkReg = /^[0-9][Z0-9_]*$/
    if (value && !checkReg.test(value)) {
      callback('只能以数字开头, 且只能包含数字和下划线')
    } else {
      callback()
    }
  }
  goBack () {
    const { history } = this.props
    history.push('/business/report')
  }

  /**
   * 提交表单
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      console.log(fieldsValue)
      const values = {
        ...Object.assign({}, fieldsValue)
      }
      values.reportTime = moment.utc(fieldsValue.reportTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ')
      values.fileList = values.fileUrl ? values.fileUrl.fileList : []
      console.log(values)
      universalFetch(`${__SERVICE_API__}device/report`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(values)
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('添加成功')
        this.props.history.push('/business/report')
        this.setState({
          loading: false
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        this.setState({
          loading: false
        })
        message.error('添加失败： ' + err.message, 10)
      })
    })
  }

  getCustomers () {
    universalFetch(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=20000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          customers: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getUsers () {
    universalFetch(`${__SERVICE_API__}sys/users?pageSize=20000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          owner: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  changeFile1 (info) {
    console.log(info)
    let fileList = info.fileList
    // 1. Limit the number of uploaded files
    //    Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-10)
    // 2. read from response and show file link
    fileList = fileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.result.url
        file.name = file.name
      }
      return file
    })
    // 3. filter successfully uploaded files according to response from server
    fileList = fileList.filter((file) => {
      const status = info.file.status
      if (status === 'done') {
        return file.response.status === 'success'
      }
      return true
    })
    console.log(fileList)
    this.setState({ fileList: fileList })
  }

  beforeUpload (file) {
    const type = file.type.toLocaleLowerCase()
    if (type.indexOf('image/') === -1) {
      message.error('只能上传图片', 3)
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return type.indexOf('image/') > -1
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { customers, loading, owner } = this.state
    const token = localStorage.getItem('asset_token')

    const props1 = {
      name: 'file',
      multiple: true,
      showUploadList: true,
      headers:{ 'X-Auth':token },
      action: `${__SERVICE_API__}static/statics`,
      onChange: this.changeFile1
    }
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label='报告名称' hasFeedback>
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请填写名字', whitespace: true }
              ]
            })(
              <Input placeholder='请填写名字' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='所属客户'>
            {getFieldDecorator('customerId', {
              rules: [
                { required: true, message: '请选择所属客户' }
              ]
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择客户'
                onChange={this.changeCustomer}
                >
                {
                  customers.map((customer, i) => {
                    return <Option key={i} value={`${customer.id}`}>
                      {customer.name}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='负责人'>
            {getFieldDecorator('userId', {
              rules: [
                { required: true, message: '请选择负责人' }
              ]
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择' onChange={this.changeUser} style={{ width: 280 }}>
                {
                  owner.map((item, i) => {
                    return <Option key={i} value={item.id}>
                      {item.name}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='报告日期'>
            {getFieldDecorator('reportTime', {
              rules: [
                { required: true, message: '请选择' }
              ]
            })(
              <DatePicker showTime placeholder='请选择报告日期' format='YYYY-MM-DD HH:mm:ss' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='描述'>
            {
              getFieldDecorator('reportDesc')(
                <Input placeholder='请填写' type='textarea' autosize={{ minRows: 6, maxRows: 30 }} />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='文件'>
            {
              getFieldDecorator('fileUrl', {})(
                <Dragger {...props1}>
                  <p className='ant-upload-drag-icon'>
                    <Icon type='inbox' />
                  </p>
                  <p className='ant-upload-text'>点击或者拖拽文件到该区域</p>
                  <p className='ant-upload-hint'>支持单个或批量上传</p>
                </Dragger>
              )
            }
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary' htmlType='submit' size='large'
              loading={loading}
              >保存</Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={this.goBack}
              >返回</Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(ReportAdd))
